//
//  ShareMenuView.m
//  bestkeep
//
//  Created by 毛韶谦 on 2017/1/6.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "ShareMenuView.h"
#import <UShareUI/UShareUI.h>

#define ShareMenuViewHeight 260


@implementation ShareMenuItemObject

-(instancetype)initWithPlatformType:(SharePlatformType)platformType {
    self = [super init];
    if(self) {
        _platformType = platformType;
        
        NSString *imageName;
        NSString *platformName;
        [UMSocialUIUtility configWithPlatformType:(UMSocialPlatformType)platformType withImageName:&imageName withPlatformName:&platformName];
        
        _image = imageName;
        _title = platformName;
    }
    return self;
}

+(instancetype)shareMenuItemObjectWithType:(SharePlatformType)platformType {
    ShareMenuItemObject *obj = [[ShareMenuItemObject alloc] initWithPlatformType:platformType];
    return obj;
}

@end





@interface ShareMenuItemCell : UICollectionViewCell

@property(nonatomic,strong,readonly) UILabel *titleLabel;
@property(nonatomic,strong,readonly) UIImageView *imageView;

@end

@implementation ShareMenuItemCell

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if(self) {
        [self initialize];
    }
    return self;
}

-(void)initialize {
    
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame) - 26)];
    _imageView.contentMode = UIViewContentModeCenter;
    [self.contentView addSubview:_imageView];
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_imageView.frame), CGRectGetWidth(self.frame), 16)];
    _titleLabel.textColor = [UIColor blackColor];
    _titleLabel.font = [UIFont systemFontOfSize:10];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:_titleLabel];
    
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        CASpringAnimation *spring = [CASpringAnimation animationWithKeyPath:@"position.y"];
        spring.damping = 5;
        spring.stiffness = 100;
        spring.mass = 1;
        spring.initialVelocity = 20;
        spring.fromValue = @(self.contentView.layer.position.y - 20);
        spring.toValue = @(self.contentView.layer.position.y);
        spring.duration = spring.settlingDuration;
        [self.contentView.layer addAnimation:spring forKey:spring.keyPath];
    }
}

-(void)layoutSubviews {
    [super layoutSubviews];
    
//    _imageView.frame = CGRectMake(0, 10, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame) - 26);
//    _titleLabel.frame = CGRectMake(0, CGRectGetMaxY(_imageView.frame), CGRectGetWidth(self.frame), 16);
}

@end

@interface ShareMenuCollectionViewFlowLayout : UICollectionViewFlowLayout

@end

@implementation ShareMenuCollectionViewFlowLayout

@end


#define SharMenuViewColumnsCount 4
NSString *const ShareMenuViewCellIdentifier = @"ShareMenuViewCellIdentifier";
@interface ShareMenuView()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong) UIView *backgroundView;
@property(nonatomic,strong) UIView *contentView;
@property(nonatomic,strong) CALayer *contentTopLine;

@property(nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong) NSArray<ShareMenuItemObject*> *dataArray;
@property(nonatomic,strong) UIButton *cancelButton;

@property(nonatomic,assign) CGFloat systemVersion;

@property(nonatomic,copy) ShareMenuViewPlatformSelection selectionBlock;

@end

@implementation ShareMenuView

-(instancetype)initWithFrame:(CGRect)frame {
    frame = [[UIScreen mainScreen] bounds];
    self = [super initWithFrame:frame];
    if(self) {
        _systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
        [self initialize];
    }
    return self;
}

-(void)initialize {
    
    self.backgroundColor = [UIColor clearColor];
    
    _backgroundView = [[UIView alloc] init];
    _backgroundView.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
    _backgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    [self addSubview:_backgroundView];
    
    UITapGestureRecognizer *backgroundTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundViewTap:)];
    backgroundTap.numberOfTapsRequired = 1;
    [_backgroundView addGestureRecognizer:backgroundTap];
    
    _contentView = [self createContentView];
    _contentView.frame = CGRectMake(0, CGRectGetHeight(self.frame), CGRectGetWidth(self.frame), ShareMenuViewHeight);
    [self addSubview:_contentView];
    
    _contentTopLine = [[CALayer alloc] init];
    _contentTopLine.backgroundColor = [UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1.00].CGColor;
    _contentTopLine.frame = CGRectMake(0, 0, CGRectGetWidth(_contentView.frame), 1 / [[UIScreen mainScreen] scale]);
    [self.contentView.layer addSublayer:_contentTopLine];
    
    ShareMenuCollectionViewFlowLayout *flowLayout = [[ShareMenuCollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollPositionCenteredVertically;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:_contentView.bounds collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor clearColor];
    [_collectionView registerClass:[ShareMenuItemCell class] forCellWithReuseIdentifier:ShareMenuViewCellIdentifier];
    _collectionView.contentInset = UIEdgeInsetsMake(0, 0, 40, 0);
    [self.contentView addSubview:_collectionView];
    [_collectionView.collectionViewLayout invalidateLayout];
    
    _cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(_contentView.frame) - 40, CGRectGetWidth(_contentView.frame), 40)];
    [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [_cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_cancelButton setBackgroundImage:[Common imageWithFrame:CGRectMake(0, 0, 1, 1) color:[UIColor whiteColor]] forState:UIControlStateNormal];
    [_cancelButton addTarget:self action:@selector(cancleButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_cancelButton];
}

-(UIView*)createContentView {
    UIView *view;
    
    if(_systemVersion >= 8.0) {
        view = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    } else {
        view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
    }
    return view;
}

-(void)layoutSubviews {
    [super layoutSubviews];
}

-(void)backgroundViewTap:(UIGestureRecognizer*)recognizer {
    [self dismiss];
}

-(void)dismiss {
    
    self.backgroundView.backgroundColor = [UIColor clearColor];
    
    CGRect contentframe = _contentView.frame;
    contentframe.origin.y = CGRectGetHeight(self.frame);
    
    [UIView animateWithDuration:0.3 animations:^{
        self.contentView.frame = contentframe;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)showWithView:(UIView*)view platformSelectionBlock:(void (^)(SharePlatformType))selectionBlock {
    
    self.selectionBlock = selectionBlock;
    
    CGRect backFrame = self.backgroundView.frame;
    backFrame.size.height = CGRectGetHeight(self.frame) - ShareMenuViewHeight;
    
    CGRect contentframe = self.contentView.frame;
    contentframe.origin.y = CGRectGetHeight(self.frame) - ShareMenuViewHeight;
    [view addSubview:self];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundView.frame = backFrame;
        self.contentView.frame = contentframe;
    } completion:^(BOOL finished) {
        
    }];
}

-(void)setItems:(NSArray<NSNumber *> *)items {
    
    _items = items;
    
    if(_items && _items.count > 0) {
        
        NSMutableArray<ShareMenuItemObject*> *array = [NSMutableArray array];
        
        for (int i = 0; i < _items.count; i++) {
            SharePlatformType type = [_items[i] integerValue];
            ShareMenuItemObject *obj = [ShareMenuItemObject shareMenuItemObjectWithType:type];
            
            [array addObject:obj];
        }
        
        _dataArray = [NSArray arrayWithArray:array];
        [_collectionView reloadData];
    } else {
        _dataArray = nil;
        [_collectionView reloadData];
    }
}

#pragma -mark collectionView delegate 
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    if(!_dataArray) {
        return 0;
    }
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataArray.count;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat width = CGRectGetWidth(collectionView.frame) / SharMenuViewColumnsCount;
    
    return CGSizeMake(width, width);
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ShareMenuItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ShareMenuViewCellIdentifier forIndexPath:indexPath];
    
    if(_systemVersion < 8.0) {
        [self configCell:cell atIndexPath:indexPath];
    }
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [self configCell:cell atIndexPath:indexPath];
}

-(void)configCell:(UICollectionViewCell*)cell atIndexPath:(NSIndexPath*)indexPath {
    
    ShareMenuItemCell *shareCell = (ShareMenuItemCell*)cell;
    
    ShareMenuItemObject *obj = _dataArray[indexPath.row];
    
    shareCell.titleLabel.text = obj.title;
    shareCell.imageView.image = [UMSocialUIUtility imageNamed:obj.image];
    [shareCell.imageView setContentScaleFactor:2];
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ShareMenuItemObject *obj = _dataArray[indexPath.row];
    if(self.selectionBlock) {
        self.selectionBlock(obj.platformType);
    }
    
    [self dismiss];
}

-(void)cancleButtonTouchUpInside:(UIButton*)sender {
    [self dismiss];
}

@end
